//
//  Essence.swift
//  FM
//
//  Created by x on 2017/10/12.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit

class Essence: NSObject {
    
    /// 社区id
    var id:String?
    
    /// 社区作者id
    var user_id:String?
    
    /// 社区标题
    var title:String?
    
    /// 社区创建时间
    var created:String?
    
    var content:String?
    
    /// 社区更新时间
    var updated:String?
    
    var jin:String?
    
    /// 社区评论数量
    var commentnum:String?
    
    /// 社区作者信息
    var user:User?
    
    var absolute_url:String?
    
    /// 保存内容图片地址
    var images:[String]? {
        didSet{
            imageURLS = [URL]()
            //1.得到所有配图的URL
            for urlString in images! {
                let url = URL(string: urlString)
                imageURLS?.append(url!)
            }
        }
    }
    
    /// 配图的urls
    var imageURLS:[URL]?
    
    
    /// 加载数据
    ///
    /// - Parameters:
    ///   - type: <#type description#>
    ///   - offset: <#offset description#>
    ///   - successCallBack: <#successCallBack description#>
    ///   - errorCallBack: <#errorCallBack description#>
    class func loadEssence(type: Int, offset:Int, finished:@escaping (_ data:[Essence]?, _ error:Error?)->()) -> Void {
        let url = "http://yiapi.xinli001.com/fm/forum-thread-list.json"
        let param = ["type":type,"flag":0,"key":"c0d28ec0954084b4426223366293d190","size":10,"offset":offset] as [String : Any]
        NetWorTools.shareNetWorkTools().get(url, parameters: param, progress: nil, success: { (_, JSON) in
            let data = (JSON as! [String:AnyObject])["data"] as! [[String:AnyObject]]
            guard data.count == 0 else {
                
                var model:[Essence] = [Essence]()
                
                for dic in data {
                    model.append(Essence(dic: dic))
                }
                
                //1.这里应该缓存图片
                cachesEssenceImages(model: model, finished: finished)
                return
            }
            
        }) { (_, error) in
            finished(nil, error)
        }
    }
    
    /// 缓存图片
    ///
    /// - Parameters:
    ///   - model: <#model description#>
    ///   - finished: <#finished description#>
    class func cachesEssenceImages(model:[Essence],finished:@escaping (_ data:[Essence], _ error:Error?)->()) -> Void {
//        print("abc".cacheDir())
        //1.创建一个队列数组
        let downloadQueue = DispatchGroup()
        
        //2.首先判断有没有图片
        for tt in model {
            if tt.imageURLS?.count != 0 {
                
                for url in tt.imageURLS! {
                    
                    downloadQueue.enter()
                    //3.缓存所有配图
                    SDWebImageManager.shared().loadImage(with: url, options: SDWebImageOptions.init(rawValue: 0), progress: nil, completed: { (_, _, _, _, _, _) in
                        downloadQueue.leave()
                    })
//                    SDWebImageManager.shared().downloadImage(with: url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) in
//                        downloadQueue.leave()
//                    })
                }
                
            }
        }
        //所有配图缓存完毕的时候
        downloadQueue.notify(queue: DispatchQueue.main) {
            //告诉我所有配图都缓存完成了.然后刷新界面
            finished(model, nil)
        }
    }
    
    
    init(dic:[String:AnyObject]) {
        super.init()
        setValuesForKeys(dic)
    }
    
    override func setValue(_ value: Any?, forKey key: String) {
        super.setValue(value, forKey: key)
        
        if "user" == key {
            user = User(dic: value as! [String:AnyObject])
            return
        }
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        //print("essence====key==========\(key)")
    }
    
    
    /// 重写模型打印方法
    override var description: String {
        let keys = ["id","user_id","title","created","updated","commentnum","user","absolute_url","images"]
        let dic = dictionaryWithValues(forKeys: keys)
        
        return "\(dic)"
    }
}
